package com.v9.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.v9.common.constant.Constants;
import com.v9.common.constant.UserConstants;
import com.v9.common.core.service.DefaultService;
import com.v9.common.dto.MenuTreeDto;
import com.v9.common.dto.MenuTypeEnum;
import com.v9.common.utils.StringUtils;
import com.v9.system.domain.MenuInfo;
import com.v9.system.domain.RoleMenu;
import com.v9.system.domain.vo.MetaVo;
import com.v9.system.domain.vo.RouterVo;
import com.v9.system.mapper.MenuInfoMapper;
import com.v9.system.mapper.RoleMenuMapper;
import com.v9.system.service.MenuInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author shilun
 */
@Service
public class MenuInfoServiceImpl extends DefaultService<MenuInfoMapper, MenuInfo> implements MenuInfoService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    protected void init() {
        super.init();
    }

    @Override
    public List<MenuInfo> queryByPin(String pin) {
        return baseMapper.queryByPin(pin);
    }

    @Override
    public List<MenuInfo> queryByRoleId(Long roleId) {
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", roleId);
        List<Long> collect = roleMenuMapper.selectList(queryWrapper).stream().map(RoleMenu::getRoleId).collect(Collectors.toList());
        return baseMapper.selectBatchIds(collect);
    }

    @Override
    public List<MenuTreeDto> buildTreeByList(List<MenuInfo> list) {
        return buildFunResTree(null, list).getChildren();
    }

    public List<RouterVo> buildMenus(List<MenuTreeDto> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (MenuTreeDto menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(!menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getIsCache(), menu.getPath()));
            List<MenuTreeDto> cMenus = menu.getChildren();
            if (cMenus != null && !cMenus.isEmpty() && cMenus.size() > 0 && menu.getMenuType() == MenuTypeEnum.M) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getName(), menu.getIcon(), !menu.getIsCache(), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    private MenuTreeDto buildFunResTree(MenuTreeDto parent, List<MenuInfo> list) {
        if (parent == null) {
            Collection<MenuInfo> rootRes = list.stream().filter(item -> item.getParentId().longValue() == 0).collect(Collectors.toList());
            MenuTreeDto roots = new MenuTreeDto();
            if (rootRes != null && rootRes.size() > 0) {
                roots.setChildren(new ArrayList<>());
            }
            rootRes.forEach(item -> {
                MenuTreeDto dto = clone(MenuTreeDto.class, item);
                roots.getChildren().add(dto);
                buildFunResTree(dto, list);
            });
            return roots;
        }
        List<MenuInfo> subItems = list.stream().filter(item -> item.getParentId() != null && Long.valueOf(parent.getId()).longValue() == item.getParentId()).collect(Collectors.toList());

        if (subItems.size() > 0) {
            parent.setChildren(new ArrayList<>());
            subItems.forEach(item -> {
                MenuTreeDto dto = clone(MenuTreeDto.class, item);
                parent.getChildren().add(dto);
                buildFunResTree(dto, list);
            });
        }

        if (subItems.size() > 1) {
            List<MenuTreeDto> subFunRes = parent.getChildren();
            Collections.sort(subFunRes, new Comparator<MenuTreeDto>() {
                @Override
                public int compare(MenuTreeDto o1, MenuTreeDto o2) {
                    if (o1.getSeq() == null) {
                        return -1;
                    }
                    return o1.getSeq() - o2.getSeq();
                }
            });
            parent.setChildren(subFunRes);
        }
        return parent;
    }


    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(MenuTreeDto menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(MenuTreeDto menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && menu.getMenuType() == MenuTypeEnum.M && !menu.getIsFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(MenuTreeDto menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(MenuTreeDto menu) {
        return menu.getParentId().intValue() == 0 && menu.getMenuType() == MenuTypeEnum.C
                && menu.getIsFrame();
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(MenuTreeDto menu) {
        return menu.getIsFrame() && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(MenuTreeDto menu) {
        return menu.getParentId().intValue() != 0 && MenuTypeEnum.M == menu.getMenuType();
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<MenuTreeDto> getChildPerms(List<MenuTreeDto> list, int parentId) {
        List<MenuTreeDto> returnList = new ArrayList<MenuTreeDto>();
        for (Iterator<MenuTreeDto> iterator = list.iterator(); iterator.hasNext(); ) {
            MenuTreeDto t = (MenuTreeDto) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<MenuTreeDto> list, MenuTreeDto t) {
        // 得到子节点列表
        List<MenuTreeDto> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MenuTreeDto tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<MenuTreeDto> getChildList(List<MenuTreeDto> list, MenuTreeDto t) {
        List<MenuTreeDto> tlist = new ArrayList<MenuTreeDto>();
        Iterator<MenuTreeDto> it = list.iterator();
        while (it.hasNext()) {
            MenuTreeDto n = (MenuTreeDto) it.next();
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MenuTreeDto> list, MenuTreeDto t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, "."},
                new String[]{"", "", "", "/"});
    }
}
